<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model;

use app\common\enum\order\DataType as DataTypeEnum;
use app\common\enum\order\DeliveryStatus as DeliveryStatusEnum;
use app\common\enum\order\OrderStatus as OrderStatusEnum;
use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\enum\order\ReceiptStatus as ReceiptStatusEnum;use app\common\library\helper;use app\common\model\Order as OrderModel;use app\common\service\Order as OrderService;use app\common\service\order\Printer as PrinterService;
use app\common\service\order\Refund as RefundService;
use app\common\service\qrcode\Piaoju as PiaojuService;
use app\store\model\OrderPayLog as payLogModel;
use cores\exception\BaseException;
use think\facade\Db;

/**
 * 订单管理
 * Class Order
 * @package app\store\model
 */
class Order extends OrderModel
{
    public function getPayLog(int $orderId)
    {
        $model = new payLogModel;

        $data['list']         = $model->where('order_id', $orderId)->select()->toArray();
        $data['total_money']  = $model->where('order_id', $orderId)->sum('pay_price');
        $data['refund_money'] = $model->where('order_id', $orderId)->sum('refund_price');
        $data['money']        = $data['total_money'] - $data['refund_money'];
        //陪护师工资
        $order               = Db::name('order')->where('order_id', $orderId)->field('day,day_price')->find();
        $data['clerk_money'] = $order['day'] * $order['day_price'];

        return $data;
    }
    /**
     * 订单详情页数据
     * @param int $orderId
     * @return Order|array|null
     */
    public function getDetailPeihu(int $orderId)
    {
        $order = static::detail($orderId, [
            'goods.image',
            'log',
            'changeLog',
            'images.file',
            'extract_clerk',
            'extractShop',
            'trade',
            'manage',
            'build', 'parkImage1', 'parkImage2', 'category',
        ]);
        // 附加数据
        static::related($order, ['user', 'address']);
        return $order;
    }
    /**
     * 订单详情页数据
     * @param int $orderId
     * @return Order|array|null
     */
    public function getDetail(int $orderId)
    {
        $order = static::detail($orderId, [
            'goods.image',
            'log',
            'delivery' => ['goods', 'express'],
            'extract_shop.logoImage',
            'extract_clerk',
            'trade',
            'build', 'parkImage1', 'parkImage2', 'driver',
        ]);
        // 附加数据
        static::related($order, ['user', 'address', 'express', 'extract']);

        return $order;
    }
    /**
     * 订单列表-代泊车
     * @param array $param
     * @return mixed
     */
    public function getListPark(array $param = [])
    {
        // 检索查询条件
        $filter = $this->getQueryFilter($param);
        // 设置订单类型条件
        $dataTypeFilter = $this->getFilterDataType3($param['dataType']);
        // 获取数据列表
        return $this->with(['goods.image', 'user.avatar'])
            ->alias('order')
            ->field('order.*')
            ->leftJoin('user', 'user.user_id = order.user_id')
            ->leftJoin('order_address address', 'address.order_id = order.order_id')
            ->where($dataTypeFilter)
            ->where($filter)
            ->where('service_type', '>', 0)
            ->where('order.is_delete', '=', 0)
            ->order(['order.create_time' => 'desc'])
            ->paginate(10);
    }
    /**
     * 订单列表
     * @param array $param
     * @return mixed
     */
    public function getListPeihu(array $param = [])
    {
        // 检索查询条件
        $filter = $this->getQueryFilter($param);
        // 设置订单类型条件
        $dataTypeFilter = $this->getFilterDataType3($param['dataType']);
        // 获取数据列表
        return $this->with(['goods.image', 'user.avatar', 'address', 'build', 'paidaner', 'manage', 'driver', 'extractClerk', 'runner', 'pdf','group'])
            ->alias('order')
            ->field('order.*')
            ->leftJoin('user', 'user.user_id = order.user_id')
            ->leftJoin('order_address address', 'address.order_id = order.order_id')
      
            ->where($dataTypeFilter)
            ->where($filter)
            ->where('order.goods_type', '=', 20)
            ->where('order.is_delete', '=', 0)
        
            ->order(['order.create_time' => 'desc'])
            ->paginate(10);
    }

    /**
     * 订单列表
     * @param array $param
     * @return mixed
     */
    public function getList(array $param = [])
    {
        // 检索查询条件
        $filter = $this->getQueryFilter($param);
        // 设置订单类型条件
        $dataTypeFilter = $this->getFilterDataTypeGoods($param['dataType']);
        // 获取数据列表
        return $this->with(['goods.image', 'user.avatar', 'address'])
            ->alias('order')
            ->field('order.*')
            ->leftJoin('user', 'user.user_id = order.user_id')
            ->leftJoin('order_address address', 'address.order_id = order.order_id')
            ->where($dataTypeFilter)
            ->where($filter)
            ->where('order.is_delete', '=', 0)
            ->where('order.goods_type', '=', 10)
            ->order(['order.create_time' => 'desc'])
            ->paginate(10);
    }
/**
 * 订单列表(全部)-商品
 * @param array $param
 * @return iterable|\think\model\Collection|\think\Paginator
 */
    public function getListAll2(array $param = [])
    {
        // 检索查询条件
        $queryFilter = $this->getQueryFilter($param);
        // 设置订单类型条件
        $dataTypeFilter = $this->getFilterDataTypeGoods($param['dataType']);

        // 获取数据列表
        $orderList = $this->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
            ->where($dataTypeFilter)

            ->where($queryFilter)
            ->where('order.is_delete', '=', 0)
            ->where('order.goods_type', '=', 10)
            ->order(['order.create_time' => 'desc'])
            ->select();

        // 加载订单关联数据
        return static::preload($orderList, [
            'goods', 'user.avatar', 'extract_shop', 'trade', 'build', 'address',
        ]);
    }

    /**
     * 订单列表(全部)-服务
     * @param array $param
     * @return iterable|\think\model\Collection|\think\Paginator
     */
    public function getListAll(array $param = [])
    {
        // 检索查询条件
        $queryFilter = $this->getQueryFilter($param);
        // 设置订单类型条件
        //$dataTypeFilter = $this->getFilterDataType3($param['dataType']);
        $serviceTypeFilter = $this->getFilterServiceType($param['serviceType']);
        // 获取数据列表
        $orderList = $this->alias('order')
            ->field('order.*')
            ->join('user', 'user.user_id = order.user_id')
        //->where($dataTypeFilter)
            ->where($serviceTypeFilter)
            ->where($queryFilter)
            ->where('order.is_delete', '=', 0)
            ->where('order.goods_type', '=', 20)
            ->order(['order.create_time' => 'desc'])
            ->select();

        // 加载订单关联数据
        return static::preload($orderList, [
            'goods', 'user.avatar', 'extract_shop', 'trade', 'build',
        ]);
    }

    /**
     * 设置检索查询条件
     * @param array $param
     * @return array
     */
    private function getQueryFilter(array $param): array
    {
        // 默认参数
        $params = $this->setQueryDefaultValue($param, [
            'searchType'    => '', // 关键词类型 (10订单号 20会员昵称 30会员ID 40收货人姓名 50收货人电话)
            'searchValue'   => '', // 关键词内容
            'orderSource'   => -1, // 订单来源
            'orderType'     => -1, // 订单类型
            'payMethod'     => '', // 支付方式
            'deliveryType'  => -1, // 配送方式
            'extractShopId' => 0,  // 自提门店ID
            'betweenTime'   => [], // 起止时间
            'userId'        => 0,  // 会员ID
        ]);
        // 检索查询条件
        $filter = [];
        // 关键词
        if (! empty($params['searchValue'])) {
           
        
             $filter[] = ['order.real_name|order.bed_no|order.room|order.mobile|order.order_no', 'like', '%'.$params['searchValue'].'%'];

            if ($params['searchType'] == 10) {

                $log = Db::name('order_pay_log')->where('order_no', $params['searchValue'])->find();
                if ($log) {
                    $filter[] = ['order.order_id', '=', $log['order_id']];
                } else {
                    $filter[] = ['order.order_no', 'like', '%' . $params['searchValue'] . '%'];
                }

            }
        }

        // 起止时间
        if (! empty($params['betweenTime'])) {
            $times    = between_time($params['betweenTime']);
            $filter[] = ['order.create_time', '>=', $times['start_time']];
            $filter[] = ['order.create_time', '<', $times['end_time'] + 86400];
        }
        // 订单来源
        $params['orderSource'] > -1 && $filter[] = ['order_source', '=', (int) $params['orderSource']];

        $params['orderType'] > -1 && $filter[] = ['order_type', '=', (int) $params['orderType']];
        // 支付方式
        ! empty($params['payMethod']) && $filter[] = ['pay_method', '=', $params['payMethod']];
        // 配送方式
        $params['deliveryType'] > -1 && $filter[] = ['delivery_type', '=', (int) $params['deliveryType']];
        // 自提门店id
        $params['extractShopId'] > 0 && $filter[] = ['extract_shop_id', '=', (int) $params['extractShopId']];
        // 会员ID
        $params['userId'] > 0 && $filter[] = ['order.user_id', '=', (int) $params['userId']];
        return $filter;
    }

    /**
     * 设置服务类型条件
     * @param string $dataType
     * @return array
     */
    private function getFilterServiceType(string $dataType): array
    {
        // 数据类型
        $filter = [];
        switch ($dataType) {
            case 'all':
                break;
            case 'peihu':

                $filter[] = ['order_type', '=', 10];

                break;
            case 'park':

                $filter[] = ['order_type', '=', 20];
                break;
            case 'pei':

                $filter[] = ['order_type', '=', 40];
                break;
            case 'run':
                $filter[] = ['order_type', '=', 30];
                break;

        }
        return $filter;
    }

    /**
     * 设置订单类型条件
     * @param string $dataType
     * @return array
     */
    private function getFilterDataType(string $dataType): array
    {
        // 数据类型
        $filter = [];
        switch ($dataType) {
            case DataTypeEnum::ALL:
                break;
            case DataTypeEnum::PAY:

                $filter[] = ['pay_status', '=', PayStatusEnum::PENDING];
                $filter[] = ['order_status', '=', OrderStatusEnum::NORMAL];
                break;
            case DataTypeEnum::DELIVERY:
                $filter = [

                    ['service_status', '=', 0],
                    ['order_status', 'in', [OrderStatusEnum::NORMAL, OrderStatusEnum::APPLY_CANCEL]],
                ];
                break;
            case DataTypeEnum::RECEIPT:
                $filter = [
                    ['pay_status', '=', PayStatusEnum::SUCCESS],
                    ['service_status', '=', 10],

                ];
                break;
            case DataTypeEnum::COMPLETE:
                $filter[] = ['order_status', '=', OrderStatusEnum::COMPLETED];
                break;
            case DataTypeEnum::APPLY_CANCEL:
                $filter[] = ['order_status', '=', OrderStatusEnum::APPLY_CANCEL];
                break;
            case DataTypeEnum::CANCEL:
                $filter[] = ['order_status', '=', OrderStatusEnum::CANCELLED];
                break;
        }
        return $filter;
    }

    /**
     * 设置订单类型条件
     * @param string $dataType
     * @return array
     */
    private function getFilterDataTypeGoods(string $dataType): array
    {
        // 数据类型
        $filter = [];
        switch ($dataType) {
            case DataTypeEnum::ALL:
                break;
            case DataTypeEnum::PAY:
                $filter[] = ['pay_status', '=', PayStatusEnum::PENDING];
                $filter[] = ['order_status', '=', OrderStatusEnum::NORMAL];
                break;
            case DataTypeEnum::DELIVERY:
                $filter = [
                    ['pay_status', '=', PayStatusEnum::SUCCESS],
                    ['delivery_status', '<>', DeliveryStatusEnum::DELIVERED],
                    ['order_status', 'in', [OrderStatusEnum::NORMAL, OrderStatusEnum::APPLY_CANCEL]],
                ];
                break;
            case DataTypeEnum::RECEIPT:
                $filter = [
                    ['pay_status', '=', PayStatusEnum::SUCCESS],
                    ['delivery_status', '=', DeliveryStatusEnum::DELIVERED],
                    ['receipt_status', '=', ReceiptStatusEnum::NOT_RECEIVED],
                ];
                break;
            case DataTypeEnum::COMPLETE:
                $filter[] = ['order_status', '=', OrderStatusEnum::COMPLETED];
                break;
            case DataTypeEnum::APPLY_CANCEL:
                $filter[] = ['order_status', '=', OrderStatusEnum::APPLY_CANCEL];
                break;
            case DataTypeEnum::CANCEL:
                $filter[] = ['order_status', '=', OrderStatusEnum::CANCELLED];
                break;
        }
        return $filter;
    }

    /**
     * 设置订单类型条件-陪护
     * @param string $dataType
     * @return array
     */
    private function getFilterDataType3(string $dataType): array
    {
        // 数据类型
        $filter = [];
        switch ($dataType) {
            case DataTypeEnum::ALL:
                break;
            case DataTypeEnum::PAY:

                $filter[] = ['pay_status', '=', PayStatusEnum::PENDING];
                $filter[] = ['order_status', '=', OrderStatusEnum::NORMAL];
                break;
            case DataTypeEnum::DELIVERY:
                $filter = [

                    ['service_status', '=', 0],
                    ['order_status', 'in', [OrderStatusEnum::NORMAL]],
                ];
                break;
            case 'paidan':
                $filter = [

                    ['paidan_time', '=', 0],
                    ['pay_status', '=', 20],
                    ['order_status', 'in', [OrderStatusEnum::NORMAL]],
                ];
                break;
            case DataTypeEnum::RECEIPT:
                $filter = [
                    ['pay_status', '=', PayStatusEnum::SUCCESS],
                    ['service_status', '=', 10],
                    ['order_status', 'in', [OrderStatusEnum::NORMAL]],

                ];
                break;
            case DataTypeEnum::COMPLETE:
                $filter[] = ['order_status', '=', OrderStatusEnum::COMPLETED];
                break;
            case DataTypeEnum::APPLY_CANCEL:
                $filter[] = ['order_status', '=', OrderStatusEnum::APPLY_CANCEL];
                break;
            case DataTypeEnum::CANCEL:
                $filter[] = ['order_status', '=', OrderStatusEnum::CANCELLED];
                break;
        }
        return $filter;
    }

    /**
     * 修改订单价格
     * @param array $data
     * @return bool
     */
    public function updatePrice(array $data): bool
    {
        if ($this['pay_status'] != PayStatusEnum::PENDING) {
            $this->error = '该订单不合法';
            return false;
        }
        // 实际付款金额
        $payPrice = helper::bcadd($data['order_price'], $data['express_price']);
        if ($payPrice <= 0) {
            $this->error = '订单实付款价格不能为0.00元';
            return false;
        }
        // 改价的金额差价
        $updatePrice = helper::bcsub($data['order_price'], $this['order_price']);
        // 更新订单记录
        return $this->save([
            'order_price'   => $data['order_price'],
            'pay_price'     => $payPrice,
            'update_price'  => $updatePrice,
            'express_price' => $data['express_price'],
        ]) !== false;
    }

    /**
     * 修改商家备注
     * @param array $data
     * @return bool
     */
    public function updateRemark(array $data): bool
    {
        return $this->save(['merchant_remark' => $data['content'] ?? '']);
    }

    /**
     * 小票打印
     * @param array $data
     * @return bool
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function printer(array $data): bool
    {
        // 实例化打印机驱动
        $Printer = new PrinterService;
        // 手动打印小票
        $status = $Printer->printEvent($this, $data['printerId']);
        if ($status === false) {
            $this->error = $Printer->getError();
        }
        return $status;
    }
    /**
     * 退款
     * @param array $data
     * @return bool|mixed
     */
    public function confirmRefund(array $data)
    {
        // 判断订单是否有效
        if (
            $this['pay_status'] != PayStatusEnum::SUCCESS
            || $this['paidan_time'] != 0
        ) {
            $this->error = '该订单不合法';
            return false;
        }
        if ($data['refund_money'] > $this['pay_price']) {
            $this->error = '退款金额不能大于实付款金额';
            return false;
        }
        // 订单取消事件
        return $this->transaction(function () use ($data) {
            if ($data['refund_money'] > 0) {
                // 执行退款操作
                if (! (new RefundService)->handle($this)) {

                    $this->error = '执行订单退款失败';
                    return false;
                }
                // 订单取消事件
                OrderService::cancelEvent($this);
            }
            // 更新订单状态
            return $this->save([
                'is_admin'     => 1,
                'order_status' => OrderStatusEnum::CANCELLED,
            ]);
        });
    }
    /**
     * 审核：用户取消订单
     * @param array $data
     * @return bool|mixed
     */
    public function confirmCancel(array $data)
    {
        // 判断订单是否有效
        if (
            $this['pay_status'] != PayStatusEnum::SUCCESS
            || $this['order_status'] != OrderStatusEnum::APPLY_CANCEL
        ) {
            $this->error = '该订单不合法';
            return false;
        }
        // 订单取消事件
        return $this->transaction(function () use ($data) {
            if ($data['status']) {
                // 执行退款操作
                if (! (new RefundService)->handle($this)) {
                    throwError('执行订单退款失败');
                }
                // 订单取消事件
                OrderService::cancelEvent($this);
            }
            // 更新订单状态
            return $this->save([
                'is_admin'     => 1,
                'order_status' => $data['status'] ? OrderStatusEnum::CANCELLED : OrderStatusEnum::NORMAL,
            ]);
        });
    }

    /**
     * 派单事件-泊车 (管理员)
     * @param array $param
     * @return bool|int
     */
    public function paidanParkEvent(array $param)
    {
        // 设置默认参数
        $param = $this->setQueryDefaultValue($param, [
            'driverId'             => null,
            'syncMpWeixinShipping' => 1,
        ]);
        return $this->confirmPaidanPark((int) $param['driverId'], (bool) $param['syncMpWeixinShipping']);
    }
/**
 * 派单事件-陪诊 (管理员)
 * @param array $param
 * @return bool|int
 */
    public function paidanRunnerEvent(array $param)
    {
        // 设置默认参数
        $param = $this->setQueryDefaultValue($param, [
            'runnerId'             => null,
            'syncMpWeixinShipping' => 1,
        ]);
        return $this->confirmPaidanRunner((int) $param['runnerId'], (bool) $param['syncMpWeixinShipping']);
    }
    /**
     * 派单事件-其他服务 (管理员)
     * @param array $param
     * @return bool|int
     */
    public function paidanEvent(array $param)
    {
        // 设置默认参数
        $param = $this->setQueryDefaultValue($param, [
            'clerkId'              => null,
            'groupId'              => 0,
            'syncMpWeixinShipping' => 1,
        ]);
        return $this->confirmPaidan((int) $param['clerkId'], $param);
    }
    public function paidanChangeEvent(array $param)
    {
        // 设置默认参数
        $param = $this->setQueryDefaultValue($param, [
            'clerkId'              => null,
            'syncMpWeixinShipping' => 1,
        ]);
        return $this->confirmPaidanChange((int) $param['clerkId'], $param);
    }
    /**
     * 自提核销事件 (管理员)
     * @param array $param
     * @return bool|int
     */
    public function extractEvent(array $param)
    {
        // 设置默认参数
        $param = $this->setQueryDefaultValue($param, [
            'clerkId'              => null,
            'syncMpWeixinShipping' => 1,
        ]);
        return $this->confirmExtract((int) $param['clerkId'], (bool) $param['syncMpWeixinShipping']);
    }
    /**
     *
     * @return bool
     */
    public function setComplate(): bool
    {

        $this->save(['order_status' => 30]);
        if ($this['order_type'] == 10) {
            Db::name('store_shop_clerk')->where('clerk_id', $this['extract_clerk_id'])
                ->update(['work_status' => 10]);
        }
        if ($this['order_type'] == 20) {
            Db::name('store_shop_driver')->where('driver_id', $this['driver_id'])
                ->update(['work_status' => 10]);
        }
        if ($this['order_type'] == 30 || $this['order_type'] == 40) {
            Db::name('store_shop_runner')->where('runner_id', $this['runner_id'])
                ->update(['work_status' => 10]);
        }

        return true;
    }
    public function setSettle($dd): bool
    {

        if ($this['is_settle'] == 1) {

        } else {

            $out_price = 0;
            $out_hour  = 0;

            $total_price = $dd['real_day'] * $this['goods'][0]['goods_price'];

            $total_price += (int) $dd['real_hour'] * $this['hour_price'] * 2;

            $out_price = (int) $dd['out_hour'] * $this['hour_price'] * 2;

            $total_price += $out_price;

            $out_hour = $dd['out_hour'];
            $shengyu  = $this['total_price'] - $this['bed_fee'] - $this['money_total'];

            if ($dd['refund_price'] + $total_price > $shengyu) {
                throwError('退款金额+工资，超过可结算金额');
            }

            //最后一次支付金额
            $last = Db::name('order_pay_log')->where('order_id', $this['order_id'])
                ->order('trade_id desc')->find();
            if ($dd['refund_price'] > $last['pay_price']) {
                throwError('退款金额大于最后一次支付金额');
            }

            if ($dd['refund_price'] > 0) {
                // 执行退款操作
                if (! (new RefundService)->handle($this, (string) $dd['refund_price'])) {
                    throwError('执行订单退款失败');
                }

            }

            //查询服务中订单
            $count = Db::name('order')->where('extract_clerk_id', $this['extract_clerk_id'])
                ->where('order_status', '=', 10)->count();
            if ($count == 1) {
                Db::name('store_shop_clerk')->where('clerk_id', $this['extract_clerk_id'])
                    ->update(['work_status' => 10]);
            }

            // 工资明细
            $data['money']       = $total_price;
            $data['order_id']    = $this['order_id'];
            $data['real_day']    = $dd['real_day'];
            $data['real_hour']   = $dd['real_hour'];
            $data['out_hour']    = $dd['out_hour'];
            $data['store_id']    = $this['store_id'];
            $data['clerk_id']    = $this['extract_clerk_id'];
            $data['create_time'] = time();
            $data['flow_type']   = 10;
            $data['describe']    = '陪护工资：' . $this['order_no'];
            Db::name('store_shop_clerk_capital')->insert($data);

            //产生票据
            $Qrcode                = new PiaojuService($this);
            $imageUrl              = $Qrcode->getImage();
            $piaoju['path']        = $imageUrl;
            $piaoju['order_id']    = $this['order_id'];
            $piaoju['store_id']    = $this['store_id'];
            $piaoju['create_time'] = time();
            $piaoju['user_id']     = $this['user_id'];
            $piaoju['name']        = $this['goods'][0]['goods_name'];
            Db::name('order_piaoju')->insert($piaoju);
        }

        $this->save(['order_status' => 30, 'is_settle' => 1,
            'real_day'                  => $dd['real_day'] + $this['real_day'],
            'real_hour'                 => $dd['real_hour'] + $this['real_hour'],
            'out_hour'                  => $out_hour + $this['real_hour'],
            'out_price'                 => $out_price]);

        return true;
    }
    /**
     * 将订单记录设置为已删除
     * @return bool
     */
    public function setDelete(): bool
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 获取已付款订单总数 (可指定某天)
     * @param null $startDate
     * @param null $endDate
     * @return int
     */
    public function getPayOrderTotal($startDate = null, $endDate = null): int
    {
        $filter = [
            ['pay_status', '=', PayStatusEnum::SUCCESS],
            ['order_status', '<>', OrderStatusEnum::CANCELLED],
        ];
        if (! is_null($startDate) && ! is_null($endDate)) {
            $filter[] = ['pay_time', '>=', strtotime($startDate)];
            $filter[] = ['pay_time', '<', strtotime($endDate) + 86400];
        }
        return $this->getOrderTotal($filter);
    }
 /**
     * 获取陪护订单总数
     * @param null $startDate
     * @param null $endDate
     * @return int
     */
    public function getPeihuOrderTotal($startDate = null, $endDate = null): int
    {
        $filter = [
            ['order_status', 'in',[10,30]],
        ];
        if (! is_null($startDate) && ! is_null($endDate)) {
            $filter[] = ['create_time', '>=', strtotime($startDate)];
            $filter[] = ['create_time', '<', strtotime($endDate)];
        }
        return $this->getOrderTotal($filter);
    }

    /**
     * 获取未发货订单数量
     * @return int
     */
    public function getNotDeliveredOrderTotal(): int
    {
        $filter = [
            ['pay_status', '=', PayStatusEnum::SUCCESS],
            ['order_type', '=', 0],
            ['delivery_status', '<>', DeliveryStatusEnum::DELIVERED],
            ['order_status', 'in', [OrderStatusEnum::NORMAL, OrderStatusEnum::APPLY_CANCEL]],
        ];
        return $this->getOrderTotal($filter);
    }

    /**
     * 获取未付款订单数量
     * @return int
     */
    public function getNotPayOrderTotal(): int
    {
        $filter = [
            ['pay_status', '=', PayStatusEnum::PENDING],
            ['order_status', '=', OrderStatusEnum::NORMAL],
        ];
        return $this->getOrderTotal($filter);
    }

    /**
     * 获取订单总数
     * @param array $filter
     * @return int
     */
    private function getOrderTotal(array $filter = []): int
    {
        // 获取订单总数量
        return $this->where($filter)
            ->where('is_delete', '=', 0)
            ->count();
    }

    //陪护已完成

   /**
     * 获取已付款订单总数 (可指定某天)
     * @param null $startDate
     * @param null $endDate
     * @return int
     */
    public function getOrderTotalComplate($startDate = null, $endDate = null): int
    {
        $filter = [
            ['pay_status', '=', PayStatusEnum::SUCCESS],
            ['order_status', '=', 30],
              ['goods_type', '=', 20],
            ['order_type', '=', 10],
        ];
        if (! is_null($startDate) && ! is_null($endDate)) {
            $filter[] = ['create_time', '>=', strtotime($startDate)];
            $filter[] = ['create_time', '<', strtotime($endDate) + 86400];
        }
        return $this->getOrderTotal($filter);
    }
  public function getOrderTotalWait($startDate = null, $endDate = null): int
    {
        $filter = [
            ['order_status', '=', 10],
            ['goods_type', '=', 20],
            ['order_type', '=', 10],
        ];
        if (! is_null($startDate) && ! is_null($endDate)) {
            $filter[] = ['create_time', '>=', strtotime($startDate)];
            $filter[] = ['create_time', '<', strtotime($endDate) + 86400];
        }
        return $this->getOrderTotal($filter);
    }
  /**
     * 获取某月的总销售额-陪护订单
     * @param null $startDate
     * @param null $endDate
     * @return float
     */
    public function getOrderTotalPricePeihu($startDate = null, $endDate = null): float
    {
        // 查询对象
        $query = $this->getNewQuery();
        // 设置查询条件
        if (! is_null($startDate) && ! is_null($endDate)) {
            $query->where('create_time', '>=', strtotime($startDate))
                ->where('create_time', '<', strtotime($endDate));
        }
        // 总销售额
        return $query
            ->where('order_status', '<>', OrderStatusEnum::CANCELLED)
            ->where('is_delete', '=', 0)
            ->where('goods_type', '=', 20)
            ->where('order_type', '=', 10)
            ->sum('pay_price');
    }

    /**
     * 获取某天的总销售额
     * @param null $startDate
     * @param null $endDate
     * @return float
     */
    public function getOrderTotalPrice($startDate = null, $endDate = null): float
    {
        // 查询对象
        $query = $this->getNewQuery();
        // 设置查询条件
        if (! is_null($startDate) && ! is_null($endDate)) {
            $query->where('pay_time', '>=', strtotime($startDate))
                ->where('pay_time', '<', strtotime($endDate) + 86400);
        }
        // 总销售额
        return $query->where('pay_status', '=', PayStatusEnum::SUCCESS)
            ->where('order_status', '<>', OrderStatusEnum::CANCELLED)
            ->where('is_delete', '=', 0)
            ->sum('pay_price');
    }

    /**
     * 获取某天的下单用户数
     * @param string $day
     * @return float|int
     */
    public function getPayOrderUserTotal(string $day)
    {
        $startTime = strtotime($day);
        return $this->field('user_id')
            ->where('pay_time', '>=', $startTime)
            ->where('pay_time', '<', $startTime + 86400)
            ->where('pay_status', '=', PayStatusEnum::SUCCESS)
            ->where('is_delete', '=', '0')
            ->group('user_id')
            ->count();
    }

    /**
     * 根据订单号获取ID集
     * @param array $orderNoArr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getOrderIds(array $orderNoArr): array
    {
        $list = (new static )->where('order_no', 'in', $orderNoArr)->select();
        $data = [];
        foreach ($list as $item) {
            $data[$item['order_no']] = $item['order_id'];
        }
        return $data;
    }
}
